package cn.yunhe.servlet;

import cn.yunhe.entity.News;
import cn.yunhe.service.NewsService;
import cn.yunhe.util.JsonServlet;
import cn.yunhe.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/GetNewsServlet")
public class GetNewsServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NewsService newsService = new NewsService();

        String title = req.getParameter("title");
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));
        int pageNum = Integer.parseInt(req.getParameter("pageNum"));

        int newsCount = newsService.getNewsCount();
        int totalPages = PageUtil.getTotalPages(newsCount);


        List<News> newsList = newsService.getNewsByPage(title, pageSize, pageNum);
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("newsList", newsList);
        maps.put("pageNum", pageNum);
        maps.put("totalPages", totalPages);
        JsonServlet.getJson(req, resp, maps);


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
